<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\User;

use App\Dao\CouponDao;
use App\Service\Service;

use Hyperf\Di\Annotation\Inject;

/**
 * 优惠券服务
 *
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Service\Admin
 */
class CouponService extends Service
{
    /**
     * @Inject
     * @var CouponDao
     */
    public $dao;

    /**
     * 注入商家服务
     *
     * @Inject
     * @var BusinessService
     */
    public $business_service;

    /**
     * 优惠券搜索接口
     * @param int $type 类型
     * @param string $keywords 搜索关键词
     * @param int $sort_type 排序方式
     * @param float|null $max_price 最大价格
     * @param float|null $min_price 最小价格
     * @return mixed
     */
    public function search(int $type, string $keywords, int $sort_type = 0, float $max_price = null, float $min_price = null)
    {
        $whereMap = [];

        $whereMap['title'] = ['like', '%' . $keywords . '%'];
        null !== $max_price && $whereMap['price'] = ['<=', $max_price];
        null !== $min_price && $whereMap['price'] = ['>=', $min_price];

        $sort = 'sort desc,created_at desc';

        switch ($sort_type) {
            // 价格从高到低
            case 1:
                $sort = 'price desc';
                break;

            // 价格从低到高
            case 2:
                $sort = 'price asc';
                break;

            // 销量
            case 3:
                $sort = 'sales desc';
                break;
        }
        $coupon_result = $this->dao->getList($type,$whereMap, $sort);

        // 按距离排序
        if ($sort_type === 4) {
            // 只查询指定商家
            $business_ids = [];
            foreach ($coupon_result as $coupon) {
                $business_ids[] = $coupon->business_id;
            }

            $longitude = $this->request->input('longitude', null);
            $latitude = $this->request->input('latitude', null);
            // 未拿到合法的位置信息
            if ($longitude === null || $latitude === null) {
                return [];
            }

            $business_geo = $this->business_service->geoCalculator(0, (float)$longitude, (float)$latitude, $business_ids);
            foreach ($business_geo as $business) {
                foreach ($coupon_result as $key => $coupon) {
                    if ($coupon->business_id !== $business['id']) continue;
                    $coupon_result[$key]['distance'] = $business['distance'] ?? 0;
                    $coupon_result[$key]['distance_desc'] = $business['distance_desc'] ?? 0;
                }
            }

            // 进行排序
            $sort_data = $coupon_result->toArray();
            array_multisort(array_column($sort_data['data'], 'distance'), SORT_ASC, $sort_data['data']);
            return $sort_data;
        }

        return $coupon_result;
    }
}